﻿namespace MetaDrive.VisualStudio.Linq
{
    using System;
    using System.Collections.Generic;
    using EnvDTE;    
    using VSLangProj;
    using VsWebSite;
    
    public sealed class ProjectReferencesIterator : IEnumerable<Project>
    {
        private readonly Project _project;

        public ProjectReferencesIterator(Project project)
        {
            if (project == null)
                throw new ArgumentNullException("project");

            this._project = project;
        }

        public IEnumerator<Project> GetEnumerator()
        {            
            if (_project.IsWebProject())
            {
                return IterateWebProjectReferences((VSWebSite)_project.Object);
            }
            else
            {
                return IterateProjectReferences((VSProject)_project.Object);
            }
        }

        private IEnumerator<Project> IterateProjectReferences(VSProject vsProject)
        {
            if (vsProject.References == null)
                yield break;

            foreach (Reference reference in vsProject.References)
            {
                if (reference.SourceProject != null)
                    yield return reference.SourceProject;
            }
        }

        private IEnumerator<Project> IterateWebProjectReferences(VSWebSite vsWebSite)
        {
            if (vsWebSite.References == null)
                yield break;

            foreach (AssemblyReference reference in vsWebSite.References)
            {
                if (reference.ReferencedProject != null)
                    yield return reference.ReferencedProject;
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }
}